package com.koala.work.yuntingche;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class EncryptUtil {

    private static final Logger log = LoggerFactory.getLogger(EncryptUtil.class);

    private static String key = "1234567890000000";

    private static String ivStr = "1234567890000000";

    /**
     *
     */
    @Test
    public void test24() {
        String abc123456 = EncryptUtil.encrypt("Abc123456");
        System.out.println(abc123456);
    }

    /**
     * @param src
     * @return
     * @Description:加密
     * @author liumin13
     */
    public static String encrypt(String src) {
        return encrypt(src, key);
    }

    /**
     * @param src
     * @return
     * @Description:加密
     * @author liumin13
     */
    public static String encrypt(String src, String key) {

        byte[] raw = key.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        byte[] encrypted = null;
        try {
            // "算法/模式/补码方式"0102030405060708
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            encrypted = cipher.doFinal(src.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            log.error("参数[" + src + "]加密发生异常");
            throw new IllegalArgumentException("加密发生异常");
        }
    }

}
